package nirvana.core.bean.json.file.storage.impl;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.AllArgsConstructor;
import nirvana.core.bean.json.file.storage.FileStorage;
import nirvana.core.properties.file.AliOssProperty;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * 【描 述】：oss 文件存储
 * 【环 境】：J2SE 11
 * 【详 细】：
 *
 * @author 李松林
 * @version v1.0 2022-10-02 新建
 * @since 2022-10-02
 */
@Component
@AllArgsConstructor
public class AliOssFileStorage implements FileStorage {

    private AliOssProperty aliOssProperty;

    @Override
    public String uploadFile(InputStream inputStream, String format) {

        String endpoint = aliOssProperty.getEndpoint();
        String accessKeyId = aliOssProperty.getAccessKeyId();
        String accessKeySecret = aliOssProperty.getAccessKeySecret();

        long expireTime = aliOssProperty.getExpireTime();

        String bucketName = aliOssProperty.getBucketName();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String key = new StringBuilder(bucketName)
                .append("/")
                .append(UUID.randomUUID())
                .append(".")
                .append(format)
                .toString();


        PutObjectRequest putObjectRequest = new PutObjectRequest(aliOssProperty.getBucketName(), key,
                inputStream);
        // 上传字符串。
        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();

        //服务器端生成url签名字串
        OSSClient Server = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        Date expiration = null;
        expiration = new Date(System.currentTimeMillis() + expireTime * 1000 * 60);
//        expiration = new Date(System.currentTimeMillis() + 1000*20);


        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(aliOssProperty.getBucketName(), key,
                HttpMethod.GET);
        //设置过期时间
        request.setExpiration(expiration);


        // 生成URL签名(HTTP GET请求)
        URL signedUrl = Server.generatePresignedUrl(request);
        String pictureUrl = signedUrl.toString();
        return pictureUrl;
    }

    @Override
    public String uploadPicture(InputStream inputStream) {
        return null;
    }

    /**
     * 拆将路径拆解为用于存储的相对路径
     * <p>
     * 1.去除
     *
     * @return
     */
    @Override
    public String dismantlingPath(String path) {

        String host = aliOssProperty.getHost();
        String bucketName = aliOssProperty.getBucketName();


        //结尾端位置
        int endIndex = path.lastIndexOf("?");
        //去除尾部
        if (endIndex != -1) {
            path = path.substring(0, endIndex);
        }


        //开头
        String start = new StringBuilder()
                .append(host)
                .append("/")
                .append(bucketName)
                .append("/")
                .toString();

        int startIndex = path.indexOf(start);
        //去除开头,获取相对路径
        if (startIndex != -1) {
            path = path.substring(startIndex);
        }
        return path;
    }


    /**
     * 将相对路径包装为可访问的决定路径
     * <p>
     * 通过保存在数据库中的相对路径获取可访问绝对路径
     *
     * @param path
     * @return
     */
    @Override
    public String packagePath(String path) {

        String endpoint = aliOssProperty.getEndpoint();
        String accessKeyId = aliOssProperty.getAccessKeyId();
        String accessKeySecret = aliOssProperty.getAccessKeySecret();

        Long expireTime = aliOssProperty.getExpireTime();
        //服务器端生成url签名字串
        OSSClient Server = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        Date expiration = null;
        if (expireTime != null) {
            expiration = new Date(System.currentTimeMillis() + expireTime * 1000 * 60);
        }

        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(aliOssProperty.getBucketName(), path,
                HttpMethod.GET);
        //设置过期时间
        request.setExpiration(expiration);


        // 生成URL签名(HTTP GET请求)
        URL signedUrl = Server.generatePresignedUrl(request);
        String fileUrl = signedUrl.toString();


        fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf("?"));
        return fileUrl;
    }
}
